package login_log_dal

import (
	"starry_sky/internal/core"
	"starry_sky/internal/dal"
	"starry_sky/internal/model"
)

type QueryLoginLogPage struct {
	core.PageSupport[model.LoginLog]
	UserName  string `json:"userName"`
	StartTime string `json:"startTime" query:"startTime" timeFormat:"2006-01-02 15:04:05" timeLocation:"Local"`
	EndTime   string `json:"endTime" query:"endTime" timeFormat:"2006-01-02 15:04:05" timeLocation:"Local"`
}

func ListLoginLogPage(query *QueryLoginLogPage) error {
	var loginLogs []model.LoginLog
	db := dal.DB.Model(&loginLogs)
	if query.UserName != "" {
		db = db.Joins("User").
			Where(`"User"."user_name" like ? or "User"."real_name" like ?`, "%"+query.UserName+"%", "%"+query.UserName+"%")
	}
	if query.StartTime != "" {
		db = db.Where(`"login_logs"."created_at" >= ?`, query.StartTime)
	}
	if query.EndTime != "" {
		db = db.Where(`"login_logs"."created_at" <= ?`, query.EndTime)
	}
	err := db.Count(&query.TotalCount).Error
	if err != nil {
		return err
	}
	err = db.Preload("User").Order("created_at desc").Offset(query.GetOffSet()).Limit(query.GetPageSize()).Find(&loginLogs).Error
	if err != nil {
		return err
	}
	query.SetData(loginLogs)
	return nil
}
